package dao;

import entity.User;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaQuery;

/**
 *
 * @author Alexander
 */
public class UserJPADAO implements  UserDAO<EntityManager> {

    private static UserJPADAO instance;

    private UserJPADAO() {
    }
    
    public static synchronized UserJPADAO getInstance() {
        if (instance == null) {
            instance = new UserJPADAO();
        }
        return instance;
    }

    @Override
    public void persist(User entity, EntityManager em) {
        em.persist(entity);
    }

    @Override
    public User find(Object id, EntityManager em) {
        return em.find(User.class, id);
    }

    @Override
    public void update(User entity, EntityManager em) {
        em.merge(entity);
    }

    @Override
    public void delete(Object id, EntityManager em) {
        User entity = em.getReference(User.class, id);
        em.remove(entity);
    }

    @Override
    public List getList(EntityManager em) {
        CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
        cq.select(cq.from(User.class));
        Query q = em.createQuery(cq);
        return q.getResultList();
    }

    @Override
    public User login(User entity, EntityManager em) {
        User user = null;
        Query q = em.createQuery("SELECT u FROM User u "
                + "WHERE u.login LIKE :username "
                + "AND u.passwd LIKE :password").setParameter("username", entity.getLogin()).setParameter("password", entity.getPasswd());

        try {
            user = (User) q.getSingleResult();
        } catch (Exception e)  {
            System.out.println(e.getMessage());
        }
        return user;
    }
    
}
